<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Require login to access cart
requireLogin();

$user_id = $_SESSION['user_id'];
$cart_items = getCartItems($pdo, $user_id);
$cart_total = getCartTotal($pdo, $user_id);

$page_title = "Shopping Cart";
?>
<?php include '../includes/header.php'; ?>

<main style="padding: 2rem 0;">
    <div class="container">
        <h1 style="margin-bottom: 2rem; color: #2c3e50;">Shopping Cart</h1>

        <?php if (empty($cart_items)): ?>
            <!-- Empty Cart -->
            <div class="card" style="text-align: center; padding: 3rem;">
                <i class="fas fa-shopping-cart" style="font-size: 4rem; color: #7f8c8d; margin-bottom: 1rem;"></i>
                <h3>Your cart is empty</h3>
                <p style="color: #7f8c8d; margin: 1rem 0 2rem;">Add some beautiful fragrances to get started!</p>
                <a href="/chuan/535g/products/" class="btn btn-primary">Continue Shopping</a>
            </div>
        <?php else: ?>
            <!-- Cart Items -->
            <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 2rem;">
                <!-- Cart Items List -->
                <div>
                    <div class="card">
                        <div class="card-header">
                            <h2>Cart Items (<?php echo count($cart_items); ?>)</h2>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Price</th>
                                        <th>Quantity</th>
                                        <th>Total</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($cart_items as $item): ?>
                                    <tr class="cart-item" data-cart-item="<?php echo $item['product_id']; ?>" data-price="<?php echo $item['price']; ?>">
                                        <td>
                                            <div style="display: flex; align-items: center; gap: 1rem;">
                                                <div class="product-image" style="width: 60px; height: 60px; border-radius: 8px; overflow: hidden;">
                                                    <?php
                                                    // Get appropriate image based on product name
                                                    $product_images = [
                                                        'Serenity Candle' => '/chuan/535g/assets/images/Serenity Candle.jpg',
                                                        'Velvet Oud Diffuser' => '/chuan/535g/assets/images/Velvet Oud Diffuser.jpg',
                                                        'Monthly Aura Box' => '/chuan/535g/assets/images/Monthly Aura Box.jpg',
                                                        'Ocean Breeze Candle' => '/chuan/535g/assets/images/Ocean Breeze Candle.jpg',
                                                        'Sandalwood Essential Oil' => '/chuan/535g/assets/images/Sandalwood Essential Oil.jpg',
                                                        'Luxury Gift Set' => '/chuan/535g/assets/images/Luxury Gift Set.jpg'
                                                    ];
                                                    $image_url = $product_images[$item['name']] ?? 'https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=400&h=300&fit=crop&crop=center';
                                                    ?>
                                                    <img src="<?php echo $image_url; ?>" alt="<?php echo htmlspecialchars($item['name']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                                                </div>
                                                <div>
                                                    <h4 style="margin: 0; color: #2c3e50;"><?php echo htmlspecialchars($item['name']); ?></h4>
                                                    <p style="margin: 0; color: #7f8c8d; font-size: 0.9rem;">Stock: <?php echo $item['stock_quantity']; ?> available</p>
                                                </div>
                                            </div>
                                        </td>
                                        <td><?php echo formatPrice($item['price']); ?></td>
                                        <td>
                                            <input type="number" 
                                                   class="quantity-input" 
                                                   data-product-id="<?php echo $item['product_id']; ?>"
                                                   value="<?php echo $item['quantity']; ?>" 
                                                   min="1" 
                                                   max="<?php echo $item['stock_quantity']; ?>"
                                                   style="width: 80px; padding: 0.5rem; border: 2px solid #ecf0f1; border-radius: 5px;">
                                        </td>
                                        <td class="item-total"><?php echo formatPrice($item['price'] * $item['quantity']); ?></td>
                                        <td>
                                            <button onclick="removeFromCart(<?php echo $item['product_id']; ?>)" 
                                                    style="background: #e74c3c; color: white; border: none; padding: 0.5rem; border-radius: 5px; cursor: pointer;">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Cart Summary -->
                <div>
                    <div class="card">
                        <div class="card-header">
                            <h2>Order Summary</h2>
                        </div>
                        
                        <div style="margin-bottom: 1.5rem;">
                            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                                <span>Subtotal:</span>
                                <span class="cart-total"><?php echo formatPrice($cart_total); ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                                <span>Shipping:</span>
                                <span><?php echo $cart_total >= 100 ? 'FREE' : '$10.00'; ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem; font-weight: bold; font-size: 1.1rem; border-top: 1px solid #ecf0f1; padding-top: 0.5rem;">
                                <span>Total:</span>
                                <span class="cart-total-final"><?php echo formatPrice($cart_total + ($cart_total >= 100 ? 0 : 10)); ?></span>
                            </div>
                        </div>

                        <?php if ($cart_total >= 100): ?>
                            <div style="background: #d4edda; color: #155724; padding: 1rem; border-radius: 5px; margin-bottom: 1.5rem; text-align: center;">
                                <i class="fas fa-gift"></i> You qualify for FREE shipping!
                            </div>
                        <?php else: ?>
                            <div style="background: #fff3cd; color: #856404; padding: 1rem; border-radius: 5px; margin-bottom: 1.5rem; text-align: center;">
                                Add $<?php echo number_format(100 - $cart_total, 2); ?> more for FREE shipping!
                            </div>
                        <?php endif; ?>

                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            <a href="checkout.php" class="btn btn-primary" style="text-align: center;">
                                <i class="fas fa-credit-card"></i> Proceed to Checkout
                            </a>
                            <a href="/chuan/535g/products/" class="btn btn-outline" style="text-align: center;">
                                <i class="fas fa-arrow-left"></i> Continue Shopping
                            </a>
                        </div>
                    </div>

                    <!-- Security Features -->
                    <div class="card" style="margin-top: 1rem;">
                        <h3 style="margin-bottom: 1rem; color: #2c3e50;">Secure Shopping</h3>
                        <div style="display: flex; flex-direction: column; gap: 0.5rem; color: #7f8c8d; font-size: 0.9rem;">
                            <div style="display: flex; align-items: center; gap: 0.5rem;">
                                <i class="fas fa-lock" style="color: #27ae60;"></i>
                                Secure checkout
                            </div>
                            <div style="display: flex; align-items: center; gap: 0.5rem;">
                                <i class="fas fa-shield-alt" style="color: #27ae60;"></i>
                                SSL encrypted
                            </div>
                            <div style="display: flex; align-items: center; gap: 0.5rem;">
                                <i class="fas fa-undo" style="color: #27ae60;"></i>
                                30-day returns
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</main>

<script>
// Update cart total when quantity changes
function updateCartTotal() {
    const cartItems = document.querySelectorAll('.cart-item');
    let subtotal = 0;
    
    cartItems.forEach(item => {
        const price = parseFloat(item.dataset.price);
        const quantity = parseInt(item.querySelector('.quantity-input').value);
        const itemTotal = price * quantity;
        
        item.querySelector('.item-total').textContent = formatPrice(itemTotal);
        subtotal += itemTotal;
    });
    
    const shipping = subtotal >= 100 ? 0 : 10;
    const total = subtotal + shipping;
    
    // Update subtotal
    document.querySelector('.cart-total').textContent = formatPrice(subtotal);
    
    // Update shipping display
    const shippingElement = document.querySelector('.cart-total').parentElement.nextElementSibling.querySelector('span:last-child');
    shippingElement.textContent = subtotal >= 100 ? 'FREE' : '$10.00';
    
    // Update total
    document.querySelector('.cart-total-final').textContent = formatPrice(total);
    
    // Update free shipping message
    updateFreeShippingMessage(subtotal);
}

// Update free shipping message
function updateFreeShippingMessage(subtotal) {
    const messageContainer = document.querySelector('.card .card-header').nextElementSibling.nextElementSibling;
    
    if (subtotal >= 100) {
        messageContainer.innerHTML = `
            <div style="background: #d4edda; color: #155724; padding: 1rem; border-radius: 5px; margin-bottom: 1.5rem; text-align: center;">
                <i class="fas fa-gift"></i> You qualify for FREE shipping!
            </div>
        `;
    } else {
        const needed = (100 - subtotal).toFixed(2);
        messageContainer.innerHTML = `
            <div style="background: #fff3cd; color: #856404; padding: 1rem; border-radius: 5px; margin-bottom: 1.5rem; text-align: center;">
                Add $${needed} more for FREE shipping!
            </div>
        `;
    }
}

// Initialize quantity controls
document.querySelectorAll('.quantity-input').forEach(input => {
    input.addEventListener('change', function() {
        updateCartTotal();
    });
});

// Initial total calculation
updateCartTotal();
</script>

<?php include '../includes/footer.php'; ?>
